<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import dDialog from '@/components/dDialog/dDialog.vue'
import { SeleteData } from '@/api/config'
import { FormRules, ElMessage } from 'element-plus'
import { Normal, NoChineseEmty, Price, PositiveInteger } from '@/util/common'
import httpService, { PackageFormType } from '@/api/physicalExaminationManager/physicalPackage'
import {FromItem} from '@/components/dFrom/dFrom'
import dFrom from '@/components/dFrom/dFrom.vue'
import useStore from '@/store/common'
import {transfDicArrData} from '@/util/common'

const {store} = useStore.setup()

const emits = defineEmits(['refreshTable'])

const title = ref('')
const showDialog = ref(false)

const formDataBase = {
  packageName: '',
  packageCode: '',
  packagePrice:'0.00',
  gender:1,
  minAge:'',
  maxAge:''
}
// 表单绑定数据
const formData = ref<PackageFormType>({...formDataBase})

// 表单数据初始化
const initData = (type, row) => {
  if (type === 'edit') {
    title.value = '编辑体检套餐'
    formData.value = {
      ...row,
      packagePrice:row.packagePrice ? '' + row.packagePrice : '0.00',
      minAge:row.minAge ? '' + row.minAge : '',
      maxAge:row.maxAge ? '' + row.maxAge : ''
    }
  } else if (type === 'add') {
    title.value = '新增体检套餐'
    formData.value = {...formDataBase}
  }
}

//表单清除控制
const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

const onConfirm = () => {
  validateFlag.value = !validateFlag.value
}
//表单验证通过事件
const onSubmit = () => {
  const params = formData.value
  httpService.savePackage(params).then(() => {
    showDialog.value = false
    ElMessage.success('保存成功！')
    emits('refreshTable')
  })

}

const openDialog = (type:string, row) => {
  initData(type, row)
  showDialog.value = true
}
const closeDialog = () => {
  resetFieldsFlag.value = !resetFieldsFlag.value
  showDialog.value = false
}

const genderList = ref<Array<SeleteData>>([])
const pastHistoryList = ref<Array<SeleteData>>([])

//表单项
const fromItems = ref<Array<FromItem>>([
  {label:'套餐编码', placeholder:'请输入套餐编码', prop:'packageCode', type:'input'},
  {label:'套餐名称', placeholder:'请输入套餐名称', prop:'packageName', type:'input'},
  {label:'套餐价格', placeholder:'请填写套餐价格', prop:'packagePrice', type:'slot', slotName:'packagePrice' },
  {label:'适用性别', placeholder:'请选择适用性别', prop:'gender', type:'selete', seleteData:genderList.value, notClearable:true},
  {label:'年龄范围', placeholder:'', prop: 'ageRange', type: 'slot', slotName:'ageRange'},
  {label:'既往史', placeholder:'', prop: 'pastHistory', type: 'selete', seleteData:pastHistoryList.value}

])
//年龄范围验证规则
const ageRangeValid = (rule, value, callback) => {
  const {minAge, maxAge} = formData.value
  if ((minAge && !PositiveInteger.test(minAge)) || (maxAge && !PositiveInteger.test(maxAge))) {
    callback(new Error('请输入正整数'))
  }
  if (minAge?.trim().length > 3 || maxAge?.trim().length > 3) {
    callback(new Error('长度不超过3个字符'))
  }
  if (minAge && maxAge && +minAge >= +maxAge) {
    callback(new Error('最小年龄应小于最大年龄'))
  }
  callback()
}

// 表单规则
const rules = reactive<FormRules>({
  packageName: [
    { required: true, message: '请输入体检套餐名称', trigger: ['change', 'blur'] },
    { message: '汉字、字母、数字、符号（非空格）', pattern: Normal, max: 50, trigger: ['change', 'blur'] },
    { message: '长度不超过50个字符', max: 50, trigger: ['change', 'blur'] }
  ],
  packageCode: [
    { required: true, message: '请输入体检套餐编码', trigger: ['change', 'blur'] },
    { message: '字母、数字、符号（非空格）', pattern: NoChineseEmty, trigger: ['change', 'blur'] },
    { message: '长度不超过50个字符', max: 50, trigger: ['change', 'blur'] }
  ],
  packagePrice:[
    {required:true, message:'请输入体检套餐价格', trigger: ['change', 'blur']},
    {message:'应输入不超过2位小数的数字', pattern:Price, trigger:['change', 'blur']},
    {message:'长度应不超过10个字符', max:10, trigger: ['change', 'blur']}
  ],
  gender:[
    {required:true, message:'请选择适用性别', trigger: ['change', 'blur']}
  ],
  ageRange:[
    {validator:ageRangeValid, trigger: ['change', 'blur']}
  ]
})
//获取字典
const getDic = () => {
  store.getDicData('gender_apply').then((res) => {
    const list:Array<SeleteData> = transfDicArrData(res)
    list.forEach((item) => {
      genderList.value.push(item)
    })
  })
  store.getDicData('past_history').then((res) => {
    const list:Array<SeleteData> = transfDicArrData(res)
    list.forEach((item) => {
      pastHistoryList.value.push(item)
    })
  })
}
onMounted(() => {
  getDic()
})

defineExpose({openDialog})
</script>
<template>
  <d-dialog
    v-if="showDialog"
    width="540px"
    :title="title"
    :show-dialog="showDialog"
    @cancel="closeDialog"
    @confirm="onConfirm"
    @close="closeDialog"
  >
    <d-from
      label-position="right"
      :label-width="120"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :rules="rules"
      method="post"
      :form-data="formData"
      :form-items="fromItems"
      :form-line-num="1"
      @submit="onSubmit"
    >
      <template #packagePrice>
        <div class="d-common-flex-full flex-gap">
          <el-input v-model="formData.packagePrice" placeholder="请输入单价" />元
          <!-- <el-input v-model="formData.packagePrice" :precision="2" :step="1" :max="9999999.99" :controls="false" />元 -->
        </div>
      </template>
      <template #ageRange>
        <div class="d-common-flex-full flex-gap">
          <el-input v-model="formData.minAge" />
          ~
          <el-input v-model="formData.maxAge" />
          岁
        </div>
      </template>
    </d-from>
  </d-dialog>
</template>
<style scoped>
.flex-gap{
  gap: 10px;
}
.el-input-number :deep(.el-input__inner){
  text-align: left;
}
</style>
